#include <semaphore.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

static int glob = 0;
static sem_t sem;

static void* thread_func(void* arg)
{
  int loops = *((int*)arg);
  int loc, j;

  for (j = 0; j < loops; j++) {
    if (sem_wait(&sem)==-1)
      printf("Failed to wait semaphore\n");
    loc = glob;
    loc++;
    glob = loc;
    if (sem_post(&sem) == -1)
      printf("Failed to post semaphore\n");
  }
  return NULL;
}

int main(int argc, char *argv[])
{
  pthread_t t1, t2;
  int loops, s;
  loops = (argc > 1)? atoi(argv[1]) :  1000000;
  
  if (sem_init(&sem, 0, 1) == -1)
    printf("Failed to init unnamed semaphore\n");
  s = pthread_create(&t1, NULL, thread_func, &loops);
  if (s != 0)
    printf("Failed to create thread 1\n");
  s = pthread_create(&t2, NULL, thread_func, &loops);
  if (s != 0)
    printf("Failed to create thread 2\n");
  s = pthread_join(t1,NULL);
  if (s != 0)
    printf("Failed to join thread 1\n");
  s = pthread_join(t2,NULL);
  if (s != 0)
    printf("Failed to join thread 2\n");

  printf("glob = %d\n", glob);
  sem_destroy(&sem);
  return 0;
}
